﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PloobsEngine.SceneControl;
using PloobsEngine.Physics;
using PloobsEngine.Modelo;
using PloobsEngine.Material;
using PloobsEngine.Engine;
using PloobsEngine.Light;
using PloobsEngine.Physics.Bepu;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using PloobsEngine.Cameras;
using PloobsEngine.Input;
using PloobsEngine.Entity;
using PloobsEngine.MessageSystem;
using PloobsEngine.Physic.PhysicObjects.BepuObject;
using BEPUphysics.UpdateableSystems.ForceFields;
using PloobsEngine.Features;
using PloobsEngine.Commands;

namespace PloobsProjectTemplate.Screens
{
    /// <summary>
    /// Basic Forward Screen
    /// </summary>
    public class Game : IScene
    {
        IModelo mXWing, mTieFighter, mLevel;

        IObject objTieFighter, objLevel;

        XWing xWing;

        SphereObject poTieFighter, poXWing;

        TriangleMeshObject poLevel;

        List<IPhysicObject> Lista;

        TimeSpan duration;

        Camera cam1;

        float amt;

        float moveSpeed;

        float turningSpeed;

        float gameSpeed = 5f;

        Vector3 pos;

        

        /// <summary>
        /// Sets the world and render technich.
        /// </summary>
        /// <param name="renderTech">The render tech.</param>
        /// <param name="world">The world.</param>
        protected override void SetWorldAndRenderTechnich(out IRenderTechnic renderTech, out IWorld world)
        {
            ///create the IWorld
            world = new IWorld(new BepuPhysicWorld(0, true, 1), new SimpleCuller());


            ///Create the deferred technich
            DeferredRenderTechnicInitDescription desc = DeferredRenderTechnicInitDescription.Default();
            desc.DefferedDebug = false;
            desc.UseFloatingBufferForLightMap = false;
            renderTech = new DeferredRenderTechnic(desc);

        }

        protected override void InitScreen(GraphicInfo GraphicInfo, EngineStuff engine)
        {
            base.InitScreen(GraphicInfo, engine);
            SkyBox skybox = new SkyBox();
            engine.AddComponent(skybox);
        }

        protected override void CleanUp(EngineStuff engine)
        {
            base.CleanUp(engine);
            engine.RemoveComponent("SkyBox");
        }

        /// <summary>
        /// Load content for the screen.
        /// </summary>
        /// <param name="GraphicInfo"></param>
        /// <param name="factory"></param>
        /// <param name="contentManager"></param>
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            Lista = new List<IPhysicObject>();

            duration = TimeSpan.FromSeconds(1);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.4f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            #region "XWING"

            //mXWing = new SimpleModel(factory, "XWing");

            //poXWing = new SphereObject(Vector3.Zero, mXWing.GetModelRadius(), 10f, 0.1f, MaterialDescription.DefaultBepuMaterial());

            ////poXWing = new BoxObject(new Vector3(0, 0, 0), 10, 10, 10, 10f, new Vector3(2), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());

            //poXWing.Entity.CollisionInformation.Events.InitialCollisionDetected += 
            //    new BEPUphysics.Collidables.Events.InitialCollisionDetectedEventHandler<BEPUphysics.Collidables.MobileCollidables.EntityCollidable>(Colidiu);

            ////poXWing.isMotionLess = true;
            /////Forward Shader (look at this shader construction for more info)
            //IShader shXWing = new ForwardXNABasicShader(new ForwardXNABasicShaderDescription(Color.Gray, Color.Red, Color.Yellow, 50f, 1f, true, true, true));

            /////Deferred material
            //IMaterial matXWing = new DeferredMaterial(shXWing);

            /////The object itself
            ////objXWing = new IObject(matXWing, mXWing, poXWing);
            ////objXWing.Name = "Thiago";
            //xWing = new XWing(poXWing, matXWing, mXWing, new Vector3(1,1,1), new Vector3(0,0,0));

            /////Add to the world
            //this.World.AddObject(xWing);

            //objXWing.PhysicObject.Velocity = new Vector3(1, 1, 1);
            //objXWing.PhysicObject.AngularVelocity = new Vector3(0, 1, 0);

            #endregion



            //#region "TieFighter"
            mTieFighter = new SimpleModel(factory, "TieFighter");

            poTieFighter = new SphereObject(new Vector3(0, 0, -150), mTieFighter.GetModelRadius(), 10f, 0.5f, MaterialDescription.DefaultBepuMaterial());
            ////poTieFighter = new BoxObject(new Vector3(0, 0, 40),10,10,10, 10f, new Vector3(0.5f), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());
            ////poTieFighter.isMotionLess = true;
            ////Lista.Add(poTieFighter);
            ////TriangleMeshObject tmesh = new TriangleMeshObject(mTieFighter, new Vector3(10,0,0), Matrix.Identity, Vector3.One);
            ///////Forward Shader (look at this shader construction for more info)
            IShader shader = new ForwardXNABasicShader(new ForwardXNABasicShaderDescription(Color.Gray, Color.Red, Color.Yellow, 50f, 1f, true, true, true)); //new DeferredNormalShader();//
            ////IShader shader = new DeferredNormalShader();
            ///////Deferred material
            IMaterial dmaterial = new DeferredMaterial(shader);
            ////IMaterial fmaterial = new ForwardMaterial(shader);
            ///////The object itself
            TieFighter tieFighter = new TieFighter(poTieFighter, dmaterial, mTieFighter);

            //objTieFighter = new IObject(dmaterial, mTieFighter, poTieFighter);
            tieFighter.OnRecieveMessage += new OnRecieveMessage(obj3_OnRecieveMessage);
            tieFighter.SetId(100);
            ///////Add to the world
            this.World.AddObject(tieFighter);
            //#endregion

            #region "Level"
            mLevel = new SimpleModel(factory, "level_texturizado");
            mLevel.SetTexture(Color.White, TextureType.AMBIENT_CUBE_MAP, 0, 0);

            IShader lShader = new ForwardXNABasicShader(new ForwardXNABasicShaderDescription(Color.Red, Color.Red, Color.Red)); //new DeferredNormalShader();

            IMaterial fmaterial = new DeferredMaterial(lShader);

            poLevel = new TriangleMeshObject(mLevel, new Vector3(0, 0, -400), Matrix.Identity, new Vector3(15), MaterialDescription.DefaultBepuMaterial());

            poLevel.isMotionLess = true;

            objLevel = new IObject(fmaterial, mLevel, poLevel);

            //Lista.Add(poLevel);

            this.World.AddObject(objLevel, true);

            IModelo mTieFighter2 = new SimpleModel(factory, "XWing");

            SphereObject tmesh2 = new SphereObject(new Vector3(0, 0, -100), mTieFighter2.GetModelRadius(),  10f, 0.5f, MaterialDescription.DefaultBepuMaterial());//new TriangleMeshObject(mTieFighter2, new Vector3(0, 0, -100), Matrix.Identity, Vector3.One);
            //TriangleMeshObject poTie = new TriangleMeshObject(mTieFighter2, new Vector3(0, 0, -400), Matrix.Identity, new Vector3(5), MaterialDescription.DefaultBepuMaterial());

            tmesh2.Entity.CollisionInformation.Events.InitialCollisionDetected +=
                new BEPUphysics.Collidables.Events.InitialCollisionDetectedEventHandler<BEPUphysics.Collidables.MobileCollidables.EntityCollidable>(Colidiu);

            IShader shader2 = new ForwardXNABasicShader(new ForwardXNABasicShaderDescription(Color.Red, Color.Red, Color.Red));

            IMaterial mat2 = new DeferredMaterial(shader2);

            xWing = new XWing(tmesh2, mat2, mTieFighter2);

            this.World.AddObject(xWing);

            #endregion



            cam1 = new Camera(xWing, Vector3.Forward);
            ICamera cam2 = new CameraStatic(new Vector3(0,0,-50f), xWing.PhysicObject.Position);
            //cam2.Target = xWing.PhysicObject.Position;

            this.World.CameraManager.AddCamera(cam1);

            this.World.CameraManager.AddCamera(cam2);

            this.World.CameraManager.SetActiveCamera(cam1.Name);

            #region "input"
            //SimpleConcreteMousePositionInputPlayable im1 = new SimpleConcreteMousePositionInputPlayable(new MouseStateChangeComplete(MouseState));
            //this.BindInput(im1);

            //SimpleConcreteKeyboardInputPlayable ik1 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.W, frente, InputMask.G2);
            //this.BindInput(ik1);

            //SimpleConcreteKeyboardInputPlayable ik2 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.S, tras, InputMask.G2);
            //this.BindInput(ik2);

            //SimpleConcreteKeyboardInputPlayable ik3 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.A, esquerda, InputMask.G2);
            //this.BindInput(ik3);

            //SimpleConcreteKeyboardInputPlayable ik4 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.D, direita, InputMask.G2);
            //this.BindInput(ik4);

            //SimpleConcreteKeyboardInputPlayable ik5 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.Q, cima, InputMask.G2);
            //this.BindInput(ik5);

            //SimpleConcreteKeyboardInputPlayable ik6 = new SimpleConcreteKeyboardInputPlayable(StateKey.DOWN, Keys.E, baixo, InputMask.G2);
            //this.BindInput(ik6);
            #endregion

            #region "SKY"

            //IModelo sky = new SimpleModel(factory, "SKY//skysphere_mesh");
            //TriangleMeshObject poSky = new TriangleMeshObject(sky, Vector3.Zero);
            //IObject objSky = new IObject(mat2, sky, poSky);

            //SkyPostEffects skyPostEffect = new SkyPostEffects();
            //skyPostEffect.list.Add(objSky);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("SKY//Black_sky");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
            #endregion

        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            amt = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 10000f;// (float)duration.TotalSeconds; 

            moveSpeed = gameTime.ElapsedGameTime.Milliseconds / 500.0f * 1f * gameSpeed;
            
            turningSpeed = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f * gameSpeed;

            
            ProcessKeyboard(gameTime);

            MoveForward(ref pos, xWing.xWingRotation, moveSpeed);

            pos = xWing.PhysicObject.Position;

        }

        /// <summary>
        /// This is called when the screen should draw itself.
        /// </summary>
        /// <param name="gameTime"></param>
        /// <param name="render"></param>
        protected override void Draw(GameTime gameTime, RenderHelper render)
        {
            xWing.PhysicObject.Rotation = Matrix.CreateFromQuaternion(xWing.xWingRotation);
            
            //try
            //{
                base.Draw(gameTime, render);
            //}
            //catch (Exception ex)
            //{ }
            ///Draw some text on the screen
            render.RenderTextComplete("Demo: Basic Screen Forward", new Vector2(GraphicInfo.Viewport.Width - 315, 15), Color.White, Matrix.Identity);

            if (shouldDraw)
            {
                render.RenderTextComplete("Collision With Object: " + objNameTemp, new Vector2(20, 60), Color.White, Matrix.Identity);
            }

           
        }

        

        #region "Controls"
        public void frente(InputPlayableKeyBoard ipk)
        {
            MoveForward(ref pos, xWing.xWingRotation, moveSpeed);
            //xWing.PhysicObject.Velocity = new Vector3(0, 0, 100);
            //xWing.PhysicObject.ApplyImpulse(xWing.PhysicObject.Position, new Vector3(0, 0, -10));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X,
            //                                            xWing.PhysicObject.Position.Y,
            //                                            xWing.PhysicObject.Position.Z + 1);
            //MoveForward(xWing.PhysicObject.Position, xWing.xWingRotation, moveSpeed);
        }

        public void tras(InputPlayableKeyBoard ipk)
        {

            MoveBackward(xWing.PhysicObject.Position, xWing.xWingRotation, moveSpeed);
            //xWing.PhysicObject.Velocity = new Vector3(0, 0, -1);
            //xWing.PhysicObject.ApplyImpulse(xWing.PhysicObject.Position, new Vector3(0, 0, 10));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X,
            //                                            xWing.PhysicObject.Position.Y,
            //                                            xWing.PhysicObject.Position.Z - 1);
        }

        public void esquerda(InputPlayableKeyBoard ipk)
        {
            xWing.leftRightRot = 0;

            xWing.leftRightRot += turningSpeed;
            //xWing.leftRightRot = MathHelper.Clamp(xWing.leftRightRot, -1f, 1f);
            Quaternion additionalRot =
                Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot); //* Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                //Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot) * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
            xWing.xWingRotation *= additionalRot;
            xWing.PhysicObject.Rotation = Matrix.Transform(xWing.PhysicObject.Rotation, xWing.xWingRotation);
            //xWing.PhysicObject.Rotation *= Matrix.CreateFromAxisAngle(Vector3.UnitY, MathHelper.ToRadians(xWing.leftRightRot)); //*
                                            //Matrix.CreateFromAxisAngle(Vector3.UnitX, MathHelper.ToRadians(xWing.upDownRot));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X + 1,
            //                                            xWing.PhysicObject.Position.Y,
            //                                            xWing.PhysicObject.Position.Z);
            
            xWing.PhysicObject.AngularVelocity = new Vector3(0, xWing.leftRightRot, 0);
            //xWing.PhysicObject.ApplyImpulse(xWing.PhysicObject.Position, new Vector3(0, 10, 0));


            //xWing.PhysicObject.Position = Vector3.Lerp(xWing.PhysicObject.Position, newPosition, amt);
            //Rotation = Vector3.Lerp(startRotation, endRotation, MathHelper.Clamp(amt,0,1));
        }

        public void direita(InputPlayableKeyBoard ipk)
        {
            xWing.leftRightRot = 0;

            xWing.leftRightRot -= turningSpeed;
            //xWing.leftRightRot = MathHelper.Clamp(xWing.leftRightRot, -1f, 1f);
            Quaternion additionalRot =
                Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot);// *Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                //Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot) * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);

            xWing.xWingRotation *= additionalRot;
            xWing.PhysicObject.Rotation = Matrix.Transform(xWing.PhysicObject.Rotation, xWing.xWingRotation);
            //xWing.PhysicObject.Rotation *= Matrix.CreateFromAxisAngle(Vector3.UnitY, MathHelper.ToRadians(xWing.leftRightRot));
                                            //Matrix.CreateFromAxisAngle(Vector3.UnitX, MathHelper.ToRadians(xWing.upDownRot));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X - 1,
            //                                            xWing.PhysicObject.Position.Y,
            //                                            xWing.PhysicObject.Position.Z);
            
            xWing.PhysicObject.AngularVelocity = new Vector3(0, xWing.leftRightRot, 0);
        }

        public void cima(InputPlayableKeyBoard ipk)
        {

            xWing.upDownRot = 0;
            xWing.upDownRot -= turningSpeed;
            //xWing.upDownRot = MathHelper.Clamp(xWing.upDownRot, -360f, 360f);
            Quaternion additionalRot =
                //Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot) * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.leftRightRot);// *Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                //Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
            xWing.xWingRotation *= additionalRot;
            //Vector3 rot = Vector3.Transform(Vector3.UnitX, xWing.xWingRotation);
            xWing.PhysicObject.Rotation = Matrix.Transform(xWing.PhysicObject.Rotation,xWing.xWingRotation);//Matrix.CreateFromAxisAngle(Vector3.UnitX, MathHelper.ToRadians(xWing.upDownRot));// *
                                                //Matrix.CreateFromAxisAngle(Vector3.UnitY, MathHelper.ToRadians(xWing.leftRightRot));
            //xWing.PhysicObject.ApplyImpulse(xWing.PhysicObject.Position, new Vector3(0, 10, 0));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X,
            //                                            xWing.PhysicObject.Position.Y + 1,
            //                                            xWing.PhysicObject.Position.Z);
        }

        public void baixo(InputPlayableKeyBoard ipk)
        {
            xWing.upDownRot = 0;
            xWing.upDownRot += turningSpeed;
            //xWing.upDownRot = MathHelper.Clamp(xWing.upDownRot, -360, 360f);
            Quaternion additionalRot =
                //Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), xWing.leftRightRot) * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.leftRightRot);// *Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
                //Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), xWing.upDownRot);
            xWing.xWingRotation *= additionalRot;
            xWing.PhysicObject.Rotation = Matrix.Transform(xWing.PhysicObject.Rotation, xWing.xWingRotation);
            //xWing.PhysicObject.Rotation *= Matrix.CreateFromAxisAngle(Vector3.UnitX, MathHelper.ToRadians(xWing.upDownRot));// * 
                                                //Matrix.CreateFromAxisAngle(Vector3.UnitY, MathHelper.ToRadians(xWing.leftRightRot));
            //xWing.PhysicObject.ApplyImpulse(xWing.PhysicObject.Position, new Vector3(0, -10, 0));
            //xWing.PhysicObject.Position = new Vector3(xWing.PhysicObject.Position.X,
            //                                            xWing.PhysicObject.Position.Y - 1,
            //                                            xWing.PhysicObject.Position.Z);
        }
        #endregion
        
        private void MoveForward(ref Vector3 position, Quaternion rotationQuat, float speed)
        {
            Vector3 addVector = Vector3.Transform(new Vector3(0,0,1f), rotationQuat);
            position += addVector *  speed;
            //xWing.PhysicObject.Position = position;
            xWing.PhysicObject.ApplyImpulse(position, addVector * speed);
        }

        private void MoveBackward(Vector3 position, Quaternion rotationQuat, float speed)
        {
            //Vector3 addVector = Vector3.Transform(new Vector3(0,0,-1), xWing.PhysicObject.Rotation);
            Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), xWing.xWingRotation);
            position += addVector * speed;
            xWing.PhysicObject.Position = position;
            //xWing.PhysicObject.ApplyImpulse(position, addVector);
        }

        private void ProcessKeyboard(GameTime gameTime)
        {
            float leftRightRot = 0;

            float turningSpeed = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
            turningSpeed *= 0.1f * gameSpeed;
            KeyboardState keys = Keyboard.GetState();
            if (keys.IsKeyDown(Keys.Right))
                leftRightRot -= turningSpeed;
            if (keys.IsKeyDown(Keys.Left))
                leftRightRot += turningSpeed;

            float upDownRot = 0;
            if (keys.IsKeyDown(Keys.Down))
                upDownRot -= turningSpeed;
            if (keys.IsKeyDown(Keys.Up))
                upDownRot += turningSpeed;

            Quaternion additionalRot = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, -1), leftRightRot) * 
                Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), upDownRot);
            
            xWing.xWingRotation *= additionalRot;

            //if (keys.IsKeyDown(Keys.Space))
            //{
            //    double currentTime = gameTime.TotalGameTime.TotalMilliseconds;
            //    if (currentTime - lastBulletTime > 100)
            //    {
            //        Bullet newBullet = new Bullet();
            //        newBullet.position = xwingPosition;
            //        newBullet.rotation = xwingRotation;
            //        bulletList.Add(newBullet);

            //        lastBulletTime = currentTime;
            //    }
            //}
        }

        #region "Collision"
        void obj3_OnRecieveMessage(IObject Reciever, Message mes)
        {
            //if (mes.Cod == "CHANGECOLOR")
            //{
            //    ///Muda a Textura do objeto
            //    Texture2D tex = GraphicFactory.CreateTexture2DColor(1, 1, StaticRandom.RandomColor());
            //    (Reciever.Modelo as SimpleModel).SetTexture(tex, TextureType.DIFFUSE);

            //    ///Recuperar quem enviou a mensagem 
            //    long senderId = mes.Sender;
            //    if (senderId != PrincipalConstants.InvalidId)
            //    {
            //        if (mes.SenderType == SenderType.OBJECT)
            //        {
            //            IObject sender = (EntityMapper.getInstance().getEntity(senderId) as IObject);
            //        }

            //    }
            //}
        }

        void Colidiu(BEPUphysics.Collidables.MobileCollidables.EntityCollidable sender, BEPUphysics.Collidables.Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair)
        {
            IObject send = BepuEntityObject.RecoverObjectFromEntity(sender.Entity);
            IObject obj = BepuEntityObject.RecoverObjectFromCollidable(other);

            ///Verifica se esta bola ja foi considerada
            ///Consider just the first collision
            //if (alreadProcessed.Contains(obj.GetId()))
            //    return;

            //alreadProcessed.Add(obj.GetId());

            ///se o objeto colidido for diferente do cenario 
            ///dont consider the island model (triangle meshes in general)
            if (obj.PhysicObject.PhysicObjectTypes != PhysicObjectTypes.TRIANGLEMESHOBJECT)
            {
                shouldDraw = true;

                ///Envia uma mensagem para o canal de comunicacao CUBO
                ///Send a message to the channel
                //Message m = new Message(send.GetId(), PrincipalConstants.InvalidId, "cubo", Priority.MEDIUM, -1, SenderType.OBJECT, null, "CHANGECOLOR");
                //MessageDeliver.SendMessage(m);

                /////Esta mensagem foi enviada sem Sender (Quem receber a mensagem nao sabera quem enviou)
                /////Envia uma mensagem para o "CUBO QUE VAI MUDAR DE COR" (lembre que o id dele eh 77 !!)
                /////Send a message to the specific  id (first cube)
                //m = new Message(PrincipalConstants.InvalidId, 77, null, Priority.MEDIUM, -1, SenderType.OBJECT, null, "CHANGECOLOR");
                //MessageDeliver.SendMessage(m);
            }

            objNameTemp = obj.Name;
        }

        bool shouldDraw;
        string objNameTemp;

        #endregion

    }
}
